package data;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionManager {

	private static ConnectionManager cm;
	private Driver dBDriver = null;
	private static Properties dbprops = new Properties();

	
	private ConnectionManager (){
		
		try {
			//Entrada de los recursos del archivo de configuración
			 InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("dbconfiguration.properties");
			//Cargamos los recursos desde "is" a "dbprops"
			 dbprops.load(is);
				 
			 }catch (Exception e1){
				 System.err.println("El fichero de propiedades de la BD no se ha encontrado");
				 e1.printStackTrace();
		}
			 
		try {
			//Guardamos la propiedad driverName de dbporops en la cadena driverName
			String driverName =  dbprops.getProperty("driverName"); 
			//Cargamos el driver
			dBDriver = (Driver) Class.forName(driverName).newInstance();
			//Registramos el driver en DriverManager
			DriverManager.registerDriver(dBDriver);
			}catch (Exception e){
				System.err.println("Unable to register JDBC Driver");
				e.printStackTrace();
			}	
		}
	
	public static synchronized ConnectionManager getInstance (){
		
		if (cm == null){
			cm = new ConnectionManager ();
		}
		return cm;
	}
	
	public Connection checkOut (){
		
		Connection conn = null;
		try{
			//Creamos las cadenas restantes cuyo valores se obtienen de dbprops
			String uri = dbprops.getProperty("dBUri");
        	String user = dbprops.getProperty("username");
        	String passwd  = dbprops.getProperty("password");
        	//Obtengo una Connection a partir de los datos enviados como parametros
			conn = DriverManager.getConnection(uri, user, passwd);
		}catch (Exception e){
			System.err.println("Unable to open a new JDBC connection");
			e.printStackTrace();
		}
		return conn;	
	}
	
	public void checkIn (Connection conn){
		
		try{
			//liberamos la conexion
			conn.close();
		}catch (SQLException e){
			e.printStackTrace();
		}
	}
	
	protected void finalize () {
		
		try {
			//Borramos dbDriver de la lista de drivers registrados dentro de DriverManager
			DriverManager.deregisterDriver(dBDriver);
		}catch (SQLException e){
			System.err.println("Unable to deregister JDBC driver");
			e.printStackTrace();
		}
	}
}
